package com.clps.algorithm03.栈;

import sun.awt.image.ImageWatched;

public class Stack1 <E>{

    //栈中的节点类
    private  class LinkNode{
        E val;
        LinkNode next;

        public LinkNode(E val, LinkNode next) {
            this.val = val;
            this.next = next;
        }

    }



    private LinkNode head;//栈顶节点,无论添加还是删除,始终是变动的
    //往栈中添加元素
    public  void push(E val){
        head = new LinkNode(val,head);
    }


    public  E pop(){
        if(head == null){
            throw  new NullPointerException();
        }

        LinkNode next = head.next;
        E result = head.val;//记录栈顶的元素的值
        head.val = null; //清楚栈顶的节点数据
        head = next;//更新栈节点
        return  result;
    }

    //获取栈顶的值,不出栈
    public  E top(){
        if(head == null){
            throw  new NullPointerException();
        }
        return head.val;
    }
}
